/**
 *请求 摄像头/麦克风 权限
 * */

function requestPermission() {
    return getDevicePermission({video: true, audio: true})
        .catch(() => getDevicePermission({video: false, audio: true}))
        .catch(() => getDevicePermission({video: true, audio: false}))
        .catch(() => true);
}
function getDevicePermission(constraints : object) {
    return global.navigator.mediaDevices
        .getUserMedia(constraints)
        .then(stream => {
            if (stream) {
                stopStreamTracks(stream);
                return true;
            }
            return Promise.reject(new Error('EmptyStreamError'));
        })
        .catch(errMsg => {
            if (errMsg && 'NotAllowedError' === errMsg.name) {
                return false;
            }
            return Promise.reject(errMsg);
        });
}
/**释放 mediaStream*/
function stopStreamTracks(stream : MediaStream) {
    if (!stream || !stream.getTracks) {
        return;
    }
    try {
        const tracks = stream.getTracks();
        tracks.forEach(it => {
            try {
                it.stop();
            } catch (errMsg) {
                // debugger;
            }
        });
    } catch (errMsg) {
        // debugger;
    }
}

export default {
    requestPermission,
}
